package org.xfy.ymcc.producer;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.xfy.common.constant.RocketConstants;
import org.xfy.ymcc.domain.CourseOrder;
import org.xfy.ymcc.domain.CourseOrderItem;
import org.xfy.ymcc.service.ICourseOrderItemService;
import org.xfy.ymcc.service.ICourseOrderService;

import javax.xml.ws.Action;
import java.util.List;
import java.util.Map;

@Component
@RocketMQTransactionListener(
        txProducerGroup = RocketConstants.ORDER_PAY_GROUP_TRANSACTION
)
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private ICourseOrderService courseOrder;
    /**
     * 执行本地事务
     * @param message
     * @param o
     * @return
     */
    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //去保存订单
        try {
            Map<String,Object> map=(Map<String, Object>) o;
            courseOrderItemService.saveBatch((List<CourseOrderItem>)map.get("list"));
            courseOrder.saveOrUpdate((CourseOrder) map.get("courseOrder"));
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 主动去查看本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //通过订单号去查询数据库完成了没有
        return RocketMQLocalTransactionState.COMMIT;
    }
}
